package com.baselibrary.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.Nullable;
import androidx.core.graphics.drawable.RoundedBitmapDrawable;
import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory;

import com.baselibrary.R;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.resource.gif.GifDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
import com.bumptech.glide.request.target.Target;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;


/**
 * @author 关忆北丶
 * @description:
 * @date :2020/6/10 17:29
 */
public class GlideUtils {
    public static void loadUserHead(Context context, String headUrl, ImageView imageView) {
        Glide.with(context)
                .load(headUrl)
                .placeholder(R.drawable.icon_def_head)
                .error(R.drawable.icon_def_head)
                .into(imageView);
    }
    public static void loadImgWH(String url, int width, int height, int errRes, ImageView view) {
        Glide.with(view.getContext()).load(url).dontAnimate().override(width, height).diskCacheStrategy(DiskCacheStrategy.AUTOMATIC).placeholder(errRes).error(errRes).into(view);
    }

    public static void loadRoundImg(final Context context, String imgUrl, ImageView view) {
        Glide.with(context).asBitmap().load(imgUrl).centerCrop().into(new BitmapImageViewTarget(view) {
            @Override
            protected void setResource(Bitmap resource) {
                RoundedBitmapDrawable circularBitmapDrawable =
                        RoundedBitmapDrawableFactory.create(context.getResources(), resource);
                circularBitmapDrawable.setCircular(true);
                view.setImageDrawable(circularBitmapDrawable);
            }
        });
    }

    public static void loadImg(Context context, int resPlaceholderId, int resErrorId, String imgUrl, ImageView view) {

        Glide.with(context)
                .load(imgUrl)
                //占位图
                .placeholder(resPlaceholderId)
                //错误图
                .error(resErrorId)
                .into(view);
    }
    public static void loadImg_101(Context context, String headUrl, ImageView imageView) {
        Glide.with(context)
                .load(headUrl)
                .placeholder(R.drawable.ic_hankol_101)
                .error(R.drawable.ic_hankol_101)
                .into(imageView);
    }
    public static void loadImg_101(Context context, int headUrl, ImageView imageView) {
        Glide.with(context)
                .load(headUrl)
                .placeholder(R.drawable.ic_hankol_101)
                .error(R.drawable.ic_hankol_101)
                .into(imageView);
    }
    public static void loadImg_228(Context context, String headUrl, ImageView imageView) {
        Glide.with(context)
                .load(headUrl)
                .placeholder(R.drawable.ic_hankol_375)
                .error(R.drawable.ic_hankol_375)
                .into(imageView);
    }
    public static void loadImg(Context context, int imgResId, ImageView view) {
        Glide.with(context).load(imgResId).into(view);
    }

    public static void loadImg(Context context, String url, ImageView view) {
        Glide.with(context).load(url).into(view);
    }

    public static void loadImgNoCache(Context context, String url, ImageView view) {
        Glide.with(context).load(url).diskCacheStrategy(DiskCacheStrategy.NONE).into(view);
    }




    public static void loadGif(Context context, int resId, ImageView imageView) {
        Glide.with(context)
                .asGif()
                .load(resId)
                .skipMemoryCache(true)//跳过内存缓存
                .diskCacheStrategy(DiskCacheStrategy.NONE)//不缓冲disk硬盘中
                .into(imageView);
    }

    public static void loadGif(Context context, String url, ImageView imageView) {
        Glide.with(context)
                .asGif()
                .load(url)
                .skipMemoryCache(false)//跳过内存缓存
                .diskCacheStrategy(DiskCacheStrategy.ALL)//不缓冲disk硬盘中
                .into(imageView);
    }


    public static void loadOneTimeGif(Context context, int resId, final ImageView imageView, final GifListener gifListener) {
        Glide.with(context)
                .asGif()
                .load(resId)
                .skipMemoryCache(true)//跳过内存缓存
                .diskCacheStrategy(DiskCacheStrategy.NONE)//不缓冲disk硬盘中
                .listener(new RequestListener<GifDrawable>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<GifDrawable> target, boolean isFirstResource) {
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(GifDrawable resource, Object model, Target<GifDrawable> target, DataSource dataSource, boolean isFirstResource) {
                        try {
                            Field gifStateField = GifDrawable.class.getDeclaredField("state");
                            gifStateField.setAccessible(true);
                            Class gifStateClass = Class.forName("com.bumptech.glide.load.resource.gif.GifDrawable$GifState");
                            Field gifFrameLoaderField = gifStateClass.getDeclaredField("frameLoader");
                            gifFrameLoaderField.setAccessible(true);
                            Class gifFrameLoaderClass = Class.forName("com.bumptech.glide.load.resource.gif.GifFrameLoader");
                            Field gifDecoderField = gifFrameLoaderClass.getDeclaredField("gifDecoder");
                            gifDecoderField.setAccessible(true);
                            Class gifDecoderClass = Class.forName("com.bumptech.glide.gifdecoder.GifDecoder");
                            Object gifDecoder = gifDecoderField.get(gifFrameLoaderField.get(gifStateField.get(resource)));
                            Method getDelayMethod = gifDecoderClass.getDeclaredMethod("getDelay", int.class);
                            getDelayMethod.setAccessible(true);
                            //设置只播放一次
                            resource.setLoopCount(1);
                            //获得总帧数
                            int count = resource.getFrameCount();
                            int delay = 0;
                            for (int i = 0; i < count; i++) {
                                //计算每一帧所需要的时间进行累加
                                delay += (int) getDelayMethod.invoke(gifDecoder, i);
                            }
                            imageView.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    if (gifListener != null) {
                                        gifListener.gifPlayComplete();
                                    }
                                }
                            }, delay);
                        } catch (NoSuchFieldException e) {
                            e.printStackTrace();
                        } catch (ClassNotFoundException e) {
                            e.printStackTrace();
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        } catch (NoSuchMethodException e) {
                            e.printStackTrace();
                        } catch (InvocationTargetException e) {
                            e.printStackTrace();
                        }
                        return false;
                    }
                }).into(imageView);
    }

    /**
     * Gif播放完毕回调
     */
    public interface GifListener {
        void gifPlayComplete();
    }

    //加载圆形图片
    public static void loadCirclePic(final Context context, String url, final ImageView imageView) {
        Glide.with(context).load(url).circleCrop().into(imageView);

    }

    public static void loadResizableImage(Context mContext, String url, ImageView ivPicture,int TotalMargin) {
        Glide.with(mContext).asBitmap().load(url).error(R.drawable.ic_hankol_375)
                .listener(new RequestListener<Bitmap>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Bitmap> target, boolean isFirstResource) {
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(Bitmap resource, Object model, Target<Bitmap> target, DataSource dataSource, boolean isFirstResource) {
                        int imageWidth = resource.getWidth();
                        int imageHeight = resource.getHeight();
                        int width = ScreenUtils.getScreenWidth(mContext) - ScreenUtils.dpToPx(TotalMargin);//固定宽度
                        //宽度固定,然后根据原始宽高比得到此固定宽度需要的高度
                        int height = width * imageHeight / imageWidth;
                        ViewGroup.LayoutParams para = ivPicture.getLayoutParams();
                        para.height = height;
                        para.width = width;
                        ivPicture.setImageBitmap(resource);
                        return false;
                    }
                })
                .into(ivPicture);
    }

    public static void loadImg_101BlackPlaceHolder(Context context, String headUrl, ImageView imageView) {
        Glide.with(context)
                .load(headUrl)
                .placeholder(R.drawable.bg_black)
                .error(R.drawable.bg_black)
                .into(imageView);
    }
    public static void loadImg_avatar(Context context, String headUrl, ImageView imageView) {
        Glide.with(context)
                .load(headUrl)
                .placeholder(R.drawable.bg_white)
                .error(R.drawable.bg_white)
                .into(imageView);
    }

}
